package com.ytzl.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.javafx.geom.transform.SingularMatrixException;
import com.ytzl.common.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws IOException {
        //获取请求头中的令牌
        String token = request.getHeader("token");

        Map<String,Object> map = new HashMap<String, Object>();

        try {
            JwtUtils.verifyToken(token);
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg","签名无效");
        }catch (TokenExpiredException e){
            map.put("msg","token过期");
            e.printStackTrace();
        }catch (AlgorithmMismatchException e){
            map.put("msg","token算法不一致");
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效");
        }
        map.put("state",false);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
